import React, { useRef, useState } from 'react'
import { Swiper, Button } from 'antd-mobile'
import type { SwiperRef } from 'antd-mobile/es/components/swiper'
import { useNavigate } from 'react-router-dom'
import './Guide.css'

const Guide: React.FC = () => {
    const [currentIndex, setCurrentIndex] = useState(0)
    const [selectedPlanType, setSelectedPlanType] = useState<string>(() => localStorage.getItem('selectedPlanType') || '')
    const navigate = useNavigate()
    const swiperRef = useRef<SwiperRef>(null)

    const guideData = [
        {
            id: 1,
            title: '欢迎来到健身空间',
            description: '提供按需训练，你可以根据自己的时间制定这些训练',
            //   image: '🏃‍♀️',
            image: '../../../public/image/nv1.jpg',
            showButtons: true
        },
        {
            id: 2,
            title: '多种训练类别',
            description: '训练类别将帮助你保持力量，保持更好的身材并养成更健康的生活方式',
            // image: '📱',
            image: '../../../public/image/nv2.jpeg',
            showButtons: false
        },
        {
            id: 3,
            title: '自定义训练模式',
            description: '创建并保存您自己的自定义训练，备名保存它们，当你准备训练时，会自动出现',
            // image: '🏋️‍♀️',
            image: '../../../public/image/nv2.jpeg',
            showButtons: false
        },
        {
            id: 4,
            title: '数百万用户的选择',
            description: '我们相信，我们的应用程序该激励你成为最好的自己',
            features: [
                '专业教练与健身指南',
                '100多个锻炼计划',
                '制定您的个人训练计划',
                '无广告'
            ],
            pricing: [
                { type: '月卡', price: '¥ 5.99', period: '每月' },
                { type: '年卡', price: '¥ 39.99', period: '每年', discount: '特惠 30%' }
            ],
            showButtons: false,
            showPricing: true
        }
    ]

    const handleNext = () => {
        if (currentIndex < guideData.length - 1) {
            const nextIndex = currentIndex + 1
            swiperRef.current?.swipeTo(nextIndex)
        }
    }

    const handleStart = () => {
        // 生成虚拟token并存储
        const virtualToken = 'virtual_token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        localStorage.setItem('userToken', virtualToken)
        localStorage.setItem('isFirstVisit', 'false')
        navigate('/gender')
    }

    const handleRegister = () => {
        navigate('/login')
    }

    const handleSkip = () => {
        localStorage.setItem('isFirstVisit', 'false')
        navigate('/index')
    }

    const handleSelectPlan = (plan: { type: string; price: string; period: string; discount?: string }) => {
        setSelectedPlanType(plan.type)
        localStorage.setItem('selectedPlanType', plan.type)
        localStorage.setItem('selectedPlan', JSON.stringify(plan))
    }

    return (
        <div className="guide-container">
            <Swiper
                ref={swiperRef}
                indicator={(total, current) => (
                    <div className="custom-indicator">
                        {Array.from({ length: total }, (_, index) => (
                            <div
                                key={index}
                                className={`indicator-dot ${index === current ? 'active' : ''}`}
                            />
                        ))}
                    </div>
                )}
                onIndexChange={setCurrentIndex}
            >
                {guideData.map((item, index) => (
                    <Swiper.Item key={item.id}>
                        <div className="guide-slide">
                            <div className="guide-image">
                                <img src={item.image} alt="" style={{width:"100%",height:"100%"}}/>
                            </div>

                            <div className="guide-content">
                                <h2 className="guide-title">{item.title}</h2>

                                {!item.showPricing ? (
                                    <p className="guide-description">{item.description}</p>
                                ) : (
                                    <div className="pricing-section">
                                        <p className="guide-description">{item.description}</p>

                                        <div className="features-list">
                                            {(selectedPlanType === '月卡' ? item.features?.filter(f => f !== '专业教练与健身指南') : item.features)?.map((feature, idx) => (
                                                <div key={idx} className="feature-item">
                                                    <span className="feature-dot">●</span>
                                                    <span>{feature}</span>
                                                </div>
                                            ))}
                                        </div>

                                        <div className={`pricing-cards ${selectedPlanType ? 'has-selection' : ''}`}>
                                            {item.pricing?.map((plan, idx) => (
                                                <div
                                                    key={idx}
                                                    className={`pricing-card ${idx === 1 ? 'featured' : ''} ${selectedPlanType === plan.type ? 'selected' : ''}`}
                                                    onClick={() => handleSelectPlan(plan)}
                                                    role="button"
                                                    tabIndex={0}
                                                >
                                                    {plan.discount && <div className="discount-badge">{plan.discount}</div>}
                                                    <div className="plan-type">{plan.type}</div>
                                                    <div className="plan-price">{plan.price}</div>
                                                    <div className="plan-period">{plan.period}</div>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                {item.showButtons && (
                                    <div className="guide-buttons">
                                        <Button
                                            className="start-button"
                                            block
                                            size="large"
                                            onClick={handleStart}
                                        >
                                            现在开始
                                        </Button>
                                        <div className="register-section">
                                            <span className="register-text">还没有账号？</span>
                                            <Button
                                                fill="none"
                                                className="register-link"
                                                onClick={handleRegister}
                                            >
                                                马上注册
                                            </Button>
                                        </div>
                                    </div>
                                )}

                                {!item.showButtons && index < guideData.length - 1 && (
                                    <div className="guide-buttons">
                                        <Button
                                            className="next-button"
                                            block
                                            size="large"
                                            onClick={handleNext}
                                        >
                                            下一步
                                        </Button>
                                    </div>
                                )}

                                {index === guideData.length - 1 && !item.showButtons && (
                                    <div className="guide-buttons">
                                        <Button
                                            className="start-training-button"
                                            block
                                            size="large"
                                            onClick={handleStart}
                                        >
                                            开始训练
                                        </Button>
                                    </div>
                                )}
                            </div>
                        </div>
                    </Swiper.Item>
                ))}
            </Swiper>

            {currentIndex > 0 && (
                <div className="skip-button">
                    <Button fill="none" onClick={handleSkip}>
                        跳过
                    </Button>
                </div>
            )}
        </div>
    )
}

export default Guide
